package com.jian.sys.controller;


import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jian.sys.common.*;
import com.jian.sys.pojo.Dept;
import com.jian.sys.pojo.Permission;
import com.jian.sys.pojo.User;
import com.jian.sys.service.PermissionService;
import com.jian.sys.service.RoleService;
import com.jian.sys.service.UserService;
import com.jian.sys.vo.DeptVo;
import com.jian.sys.vo.PermissionVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 剑
 * @since 2020-01-08
 */
@RestController
@RequestMapping("/menu")
public class MenuController {


    @Autowired
    PermissionService permissionService;
    @Autowired
    RoleService roleService;
    @Autowired
    UserService userService;
    /**
     * 获取加载菜单数据
     * @return
     */
    @GetMapping("/loadIndexLeftMenuJson")
    public DataGridView loadIndexLeftMenuJson(){
        QueryWrapper<Permission> wrapper = new QueryWrapper<>();
        wrapper.eq("type", Constant.TYPE_MENU);
        wrapper.eq("available",Constant.AVAILABLE_TRUE);
        List<Permission> list = null;
        User user = (User) WebUtils.getSession().getAttribute("user");
        if(user.getType() == Constant.USER_TYPE_SUPER)
        {
            list = permissionService.list(wrapper);

        }else
        {
            //根据用户的权限进行菜单划分 //根据用户ID+角色+权限去查询
            Integer userId=user.getId();
            //获取用户的角色ID
            List<Integer>roleIds=this.userService.queryUserRoleByUid(userId);
            //通过角色ID获取权限和菜单
            Set<Integer> pIds=new HashSet<>();
            for (Integer roleId : roleIds) {
                List<Integer> permissionId=this.roleService.queryRolePermissionByRid(roleId);
                for (Integer pid : permissionId) {
                    pIds.add(pid);
                }
            }
            if (pIds.size()>0){
                QueryWrapper<Permission> qw = new QueryWrapper<>();
                qw.in("id",pIds);
                qw.eq("type",Constant.TYPE_MENU);
                list = this.permissionService.list(qw);
            }else {
                list =new ArrayList<>();
            }
        }
        //层级划分
        List<TreeNode> treeNodeList=new ArrayList<>();
        for (Permission p : list) {
            Integer id = p.getId();
            Integer pid = p.getPid();
            String title = p.getTitle();
            String icon = p.getIcon();
            String href = p.getHref();
            Boolean spread = p.getOpen()>0 ? Constant.MENU_SPREAD_TRUE : Constant.MENU_SPREAD_FALSE;
            treeNodeList.add(new TreeNode(id,pid,title,icon,href,spread));
        }
        //划分子节点
        List<TreeNode> list1 = TreeNodeBuilder.build(treeNodeList, 1);
        return new DataGridView(list1);
    }


    @RequestMapping("/loadMenuMenuDtreeJson")
    public DataGridView loadMenuTitle(){
        List<Permission> list = permissionService.list();
        List<TreeNode> treeNodes = new ArrayList<>();
        for (Permission menu : list) {
            Integer id = menu.getId();
            Integer pid = menu.getPid();
            String title = menu.getTitle();
            Boolean spread=menu.getOpen()== Constant.DEPT_TRUE?Constant.MENU_SPREAD_TRUE:Constant.MENU_SPREAD_FALSE;
            treeNodes.add(new TreeNode(id,pid,title,spread));
        }
        return new DataGridView(treeNodes);
    }
    /**
     * 查询所有和模糊查询
     */
    @RequestMapping("/loadAllMenu")
    public DataGridView loadAllMenu(PermissionVo menuVo){
        IPage<Permission> page = new Page<>(menuVo.getPage(),menuVo.getLimit());
        QueryWrapper<Permission> wrapper = new QueryWrapper<>();
        wrapper.eq(menuVo.getId()!=null,"id",menuVo.getId()).or().eq(menuVo.getId()!=null,"pid",menuVo.getId());
        wrapper.like(StringUtils.isNotBlank(menuVo.getTitle()),"title",menuVo.getTitle());
        wrapper.eq("type",Constant.TYPE_MENU);
        wrapper.orderByAsc("ordernum");
        this.permissionService.page(page,wrapper);
        return new DataGridView(page.getTotal(),page.getRecords());
    }

    /**
     * 获取最大的排序值
     * @return
     */
    @RequestMapping("/getMaxOrderNum")
    public Map<String,Object> getMaxOrderNum(){
        Map<String,Object> maxOrderNum =new HashMap<>();
        QueryWrapper<Permission> wrapper = new QueryWrapper<>();
        wrapper.orderByDesc("ordernum");
        List<Permission> list = this.permissionService.list(wrapper);
        if(list.size()>0) {
            maxOrderNum.put("value", list.get(0).getOrdernum() + 1);
        }
        else {
            maxOrderNum.put("value",1);
        }
        return maxOrderNum;
    }




    /**
     * 添加
     * @param menuVo
     * @return
     */
    @RequestMapping("/addMenu")
    public ResultObj addMenu(PermissionVo menuVo){
        try {
            menuVo.setType(Constant.TYPE_MENU);
            this.permissionService.save(menuVo);
            return ResultObj.ADD_SUCCESS;
        }catch (Exception e){
            e.printStackTrace();
            return ResultObj.ADD_ERROR;
        }
    }
    /**
     * 修改
     * @param menuVo
     * @return
     */
    @RequestMapping("/updateMenu")
    public ResultObj updateMenu(PermissionVo menuVo){
        try {
            menuVo.setType(Constant.TYPE_MENU);
            this.permissionService.updateById(menuVo);
            return ResultObj.UPDATE_SUCCESS;
        }catch (Exception e){
            e.printStackTrace();
            return ResultObj.UPDATE_ERROR;
        }
    }
    /**
     * 检查删除的是否有子节点
     */
    @RequestMapping("/checkDeleteMenuChildren")
    public Map<String,Object>checkDeleteMenuChildren(PermissionVo menuVo){
        Map<String,Object> map=new HashMap<>();
        QueryWrapper<Permission> wrapper = new QueryWrapper<>();
        wrapper.eq(menuVo.getId()!=null,"pid",menuVo.getId());
        List<Permission> list = this.permissionService.list(wrapper);
        if (list.size()>0){
            map.put("value",true);
        }else{
            map.put("value",false);
        }
        return map;
    }
    /**
     * 删除
     * @param id
     * @return
     */
    @RequestMapping("/deleteMenu")
    public ResultObj deleteMenu(Integer id){
        try{
            this.permissionService.removeById(id);
            return ResultObj.DELETE_SUCCESS;
        }catch (Exception e){
            e.printStackTrace();
            return ResultObj.DELETE_ERROR;
        }
    }
}

